package com.example.weight.greenSeasons.waterDeal;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.navigation.SijiqingFlocculationNavActivity;
import com.example.weight.util.uriUtils;
import com.example.weight.wormHandle.cultivate.SmallWormBreedingIncoming;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SendWaterTable extends AppCompatActivity {
    private TitleBar titleBar;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    private TextView tvDate;
    private EditText etTrain, etWeight, etDeliverPerson, etRecordPerson, etRemarks;
    private Button btnSave;
    private String factory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent previousIntent = getIntent();
        factory = previousIntent.getStringExtra("factory");

        setContentView(R.layout.activity_send_water_table);

        titleBar=findViewById(R.id.titleBar);
        tvDate = findViewById(R.id.send_water_date);
        tvDate.setText(simpleDateFormat.format(new Date()));
        etTrain = findViewById(R.id.et_train_number);
        etWeight = findViewById(R.id.et_weight);
        etDeliverPerson = findViewById(R.id.et_deliver_person);
        etRecordPerson = findViewById(R.id.et_record_person);
        etRecordPerson.setText(getIntent().getStringExtra("name"));
        etRemarks = findViewById(R.id.et_remarks);
        btnSave = findViewById(R.id.btn_save);

        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                SendWaterTable.this.finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }


        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void bulk_import(View view){
//        批量导入
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, "uri");
        startActivityForResult(intent, 1);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == Activity.RESULT_OK){
            Uri uri = null;
            if(data != null){
                uri = data.getData();
                String path = uriUtils.getPath(SendWaterTable.this, uri);
                Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void save(View view) {
        if (etTrain == null) {
            Toast.makeText(this, "请填写车次", Toast.LENGTH_SHORT).show();
            return;
        }
        if(etWeight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写净重", Toast.LENGTH_SHORT).show();
            return;
        }
        if(etDeliverPerson.getText().toString().equals("")) {
            Toast.makeText(this, "请填写送水人", Toast.LENGTH_SHORT).show();
            return;
        }
        if(etRecordPerson.getText().toString().equals("")) {
            Toast.makeText(this, "请填写记录人", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/sjqWaterProductionDeliverWater/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")){
                                            Toast.makeText(SendWaterTable.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        }
                                        else
                                            Toast.makeText(SendWaterTable.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(SendWaterTable.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("LB", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("train_number", etTrain.getText().toString());
                            map.put("weight", etWeight.getText().toString());
                            map.put("deliver_person", etDeliverPerson.getText().toString());
                            map.put("recording_person", etRecordPerson.getText().toString());
                            map.put("remarks", etRemarks.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}